import os
import logging.handlers

import sys
import importlib

importlib.reload(sys)
import logging


log_dir = './logs'
if not os.path.exists(log_dir):
    os.mkdir(log_dir)
log_filename = 'RunInfo.log'


def log_init():

    # 设置格式
    log_format_str1 = '[%(asctime)s %(levelname)s] %(message)s'
    format = logging.Formatter(log_format_str1)

    # 根据 log 标识获取 log
    root = logging.getLogger("my_log")

    # 加入文件句柄, 按大小或日期回滚
    # h = logging.handlers.RotatingFileHandler(log_path, mode='a', encoding="utf-8")
    h = logging.handlers.TimedRotatingFileHandler(
        log_dir + os.sep + log_filename, encoding='utf-8',
        when='D',
        interval=1,
        backupCount=5
    )
    h.suffix = "%Y%m%d%H%M%S.log"
    h.setFormatter(format)

    # 加入输出流句柄
    log_format_str2 = '[%(asctime)s-%(levelname)s-(%(filename)s:%(lineno)d)] %(message)s'
    format2 = logging.Formatter(log_format_str2)
    s = logging.StreamHandler()
    s.setFormatter(format2)

    root.addHandler(h)
    root.addHandler(s)
    root.setLevel(logging.INFO)
    return root

log_init()
mylog = logging.getLogger("my_log")